#!/usr/bin/perl
use Cwd 'abs_path';
use Getopt::Long;
&Getopt::Long::GetOptions(
'config=s'      => \$config
);
$line = abs_path($0);
chomp $line;
@DR_array = split('/',$line);
pop(@DR_array);
pop(@DR_array);
$dir = join("/",@DR_array);

#package will help to read config paramater
require "$dir/bin/CONFIG.pl";
getDetails($config);
my $input_direc = $config{"INPUT_FOLDER"};
my $output_direc = $config{"OUTPUT_FOLDER"};
my $dirtemp = $config{"TEMP_FOLDER"};
my $file_error = $config{"ERROR_FILE"};
my $file_sampleqc = $config{"QC_FILE"};
print "INPUT DIREC:$input_direc\tOUTPUT DIREC:$output_direc\tTEMP DIREC:$dirtemp\tERROR FILE:$file_error\tSAMPLE QC:$file_sampleqc\n";
chomp $input_direc;
chomp $output_direc;
chomp $dirtemp;
chomp $file_error;
chomp $file_sampleqc;
if($input_direc eq "")
{
	die "entered input directory is empty\n";
	
}
if($output_direc eq "")
{
        die "entered output directory is empty\n";

}
if($dirtemp eq "")
{
        die "entered temporary directory is empty\n";

}
if($file_error eq "")
{
        die "entered error file is empty\n";

}
if($file_sampleqc eq "")
{
        die "entered sample qc is empty\n";

}
#creating the output directory
system("mkdir -p $output_direc");
$input_direc =~ s/\/$//;
$output_direc =~ s/\/$//;

#creating the temp directory
if (!(-d $dirtemp))
{
        system("mkdir -p $dirtemp");
}
$round = sprintf("%.0f", rand()*time());
$tempdir ="temp$round";
system("mkdir $dirtemp/$tempdir");

#reading probe to gene/entrezid mapping information
open PROBE,"< $dir/bin/probes_genes_entrezid" or die "no file $dir/bin/probes_genes_entrezid $!";
#open PROBE,"< $dir/bin/agilent_plfm_3.txt" or die "no file  $dir/bin/probes_genes_entrezid $!";
#storing probeid to entrez ID
while(<PROBE>)
{
	chomp($_);
	if($_ !~ m/\,/)
	{
		$_ =~ s/\|/\t/g;
		$_ =~ s/\r//g;
		$_ =~ s/ //g;
		@array = split(/\t/,$_);
		#print $array[0]."\t".$array[1]."\n";
		if($array[0] ne "" )
		{
			$hash{$array[0]} = $array[2];
			print "test $array[0] $array[2]\n";
		}
	}
}
close(PROBE);
#reading the input directory
opendir(DIR, $input_direc) || die $!;
#writing the sample qc file
open SAMPLEQC,">$output_direc/$file_sampleqc";
print SAMPLEQC "SAMPLE_NAME\tQC_SAMPLE_FLAG\tPRESENT_ABSENT\tBARCODE\tMAD\tSPIKE\tQC_SAMPLE_IND\tQC_SAMPLE_FLAG\n";
open ERROR,">$output_direc/$file_error";
print ERROR "ID_TYPE\tID\tSEVERITY\tMSG_CODE\tDETAILS\n";

#read files in the directory 
while($line = readdir(DIR)) 
{
	if($line ne "." && $line ne ".." && $line !~ m/^config/)
	{
		print "$input_direc/$line\n";
		#reading multiple files
		open BUFF,"< $input_direc/$line" or die "no file $input_direc/$line exists $!";
		open WRBUFF,">$dirtemp/$tempdir/inputfile.txt";
		$line_file = <BUFF>;
		chomp($line_file);	
		#$line_file = <BUFF>;
		@SampleID = split(/\t/,$line_file);
		$line_file = <BUFF>;
		#print $line_file."\t";
		@array=();
		my $num_test = 0;
		my $num_test1 = 0;
		#print "sucess : $num_test\t$num_test1\n";
		#entrez id to expr value
		while($line_file = <BUFF>)
		{
			chomp($line_file);
			@array = split(/\t/,$line_file);
			if(exists($hash{$array[0]}) && $hash{$array[0]} ne "" && $array[1] ne "" && $array[1] ne "null")
			{
				print WRBUFF $hash{$array[0]}."\t".$array[1]."\n";
				#print  $hash{$array[0]}."\t".$array[1]."\n";
				$num_test++;
			}
			$num_test1++;
		}
		#print "$num_test\t$num_test1\n";
		close(BUFF);
		close(WRBUFF);
		#Rscript uses tukey biweight method to deal with multiple expr value for one entrez id
		$sys = "/usr/local/biotools/r/R-2.12.2/bin/Rscript $dir/bin/Rscript_agilent.R ".'"'."$dirtemp/$tempdir".'"';
		#print "$sys\n";
		system($sys);
		if (!(-e "$dirtemp/$tempdir/outfile.txt")) 
		{
        		print ERROR "SAMPLEID\t$input_direc/$line\tERROR\t$SampleID[1]\tRSCRIPT FILE FORMAT ERROR $SampleID[1]\n";
			#die;
		}
		else
		{
			#system("mv $dirtemp/$tempdir/outfile.txt $output_direc/$line");
			if(exists($sample{$SampleID[1]}))
			{
				print ERROR "SAMPLEID\t$input_direc/$line\tERROR\t$SampleID[1]\tDUPLICATE ALIQOT IDS $SampleID[1]\n";
			}
			else
			{	
				$sample{$SampleID[1]} = 1;
				system("mv $dirtemp/$tempdir/outfile.txt $output_direc/$SampleID[1]");
				#system("mv $dirtemp/$tempdir/outfile.txt $output_direc/$line");
			}
		}
		#print "$output_direc/$line\n";
		#print SAMPLEQC "$line\tY\tNA\tNA\tNA\tNA\tNA\tNA\n";
		print SAMPLEQC "$SampleID[1]\tY\tNA\tNA\tNA\tNA\tNA\tNA\n";
		
		#system("rm $dirtemp/$tempdir/*");
	}
}
system("rm $dirtemp/$tempdir/*");
system("rm rf $dirtemp/$tempdir");
closedir(DIR);
close(SAMPLEQC);
close(ERROR);
